<template>
    <div class="goodslist-container">
        <van-nav-bar title="商品列表" left-text="返回" @click-left="$router.back()" left-arrow fixed />
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                <div @click="$router.push(`/detail?id=${item.id}`)" class="good-item" v-for="item in list"
                    :key="item.id">
                    <img v-lazy="item.img_url" style="width: 80px;">
                    <div>
                        <div> {{ item.title }} </div>
                        <div> {{ dateFormat(item.add_time) }} </div>
                    </div>
                </div>
            </van-list>
        </van-pull-refresh>
        <van-back-top class="custom" offset="300" right="30" bottom="40">Top</van-back-top>
    </div>

</template>

<script setup>
import { ref } from 'vue';
import { dateFormat } from '../util'
import { fetchGoodsList } from '../api/goods'

const list = ref([]); // 数据源
const page = ref(1);
const pagesize = ref(5);
const loading = ref(false); // 是否是加载中
const finished = ref(false); // 是否加载完毕
const refreshing = ref(false); // 是否刷新中


// ajax获取商品
const fetchGoodsListData = async () => {
    loading.value = true // 加载中
    let data = await fetchGoodsList(page.value, pagesize.value)
    if (data.message.length < pagesize.value) {
        // 说明此页面数据已经加载完毕了，也代表下一页没有数据了
        finished.value = true
    }
    list.value = [...list.value, ...data.message]
    loading.value = false // 加载结束
    page.value++
}

const onLoad = () => {
    fetchGoodsListData()
};


// 下拉刷新方法
const onRefresh = () => {
    page.value = 1
    if (refreshing.value) {
        // 清空数据
        list.value = [];
        // 取消刷新状态
        refreshing.value = false;

        // 代表数据没有加载完毕
        finished.value = false
    }
    // 重新加载数据
    onLoad();
};

</script>

<style lang="scss" scoped>
.goodslist-container {
    padding-top: 48px;

    .van-pull-refresh {
        .van-list {
            .good-item {
                display: flex;
                // justify-content: space-between;

                img {
                    width: 100px;
                    height: 100px;
                }
            }
        }
    }

    .custom {
        width: 80px;
        font-size: 14px;
        text-align: center;
    }
}
</style>